package gateway.model.dto;

import com.google.common.collect.Lists;
import common.model.enums.UserValidEnum;
import common.model.po.SysAuthority;
import common.model.po.SysRole;
import common.model.po.SysUser;
import common.model.po.SysWebConfig;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.Collection;
import java.util.Date;
import java.util.List;

/**
 * 安全认证用户详情信息
 *
 * @author 米泽鹏
 * @since 2021-07-31 4:56 下午
 */
@Data
@NoArgsConstructor
@Slf4j
public class SecurityUser implements UserDetails {

	/**
	 * 当前登录用户
	 */
	private transient SysUser user;

	/**
	 * 当前用户所拥有的角色
	 */
	private transient List<SysRole> roleList = Lists.newArrayList();

	/**
	 * 当前用户所拥有的所有权限
	 */
	private transient List<SysAuthority> authorityList = Lists.newArrayList();

	/**
	 * 前端布局配置
	 */
	private transient SysWebConfig webConfig;

	private transient String token;

	private transient Date expire;

	/**
	 * 获取当前用户所具有的角色id
	 */
	@Override
	public Collection<? extends GrantedAuthority> getAuthorities() {
		Collection<GrantedAuthority> grantedAuthorityCollection = Lists.newArrayList();
		roleList.stream().map(role -> new SimpleGrantedAuthority(String.valueOf(role.getId()))).forEach(grantedAuthorityCollection::add);
		return grantedAuthorityCollection;
	}

	@Override
	public String getPassword() {
		return user == null ? null : user.getPassword();
	}

	public Long getUserId() {
		return user == null ? null : user.getId();
	}

	@Override
	public String getUsername() {
		return user == null ? null : user.getUsername();
	}

	@Override
	public boolean isAccountNonExpired() {
		return user != null;
	}

	@Override
	public boolean isAccountNonLocked() {
		return user != null;
	}

	@Override
	public boolean isCredentialsNonExpired() {
		return user != null;
	}

	@Override
	public boolean isEnabled() {
		return user != null && UserValidEnum.VALID.getValue().equals(user.getValid());
	}

}
